<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>华容道拼图小游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#10B981',
                        accent: '#F59E0B',
                        dark: '#1F2937',
                        light: '#F9FAFB'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .puzzle-tile {
                @apply flex items-center justify-center text-white font-bold rounded-lg shadow-lg transition-all duration-300 cursor-pointer hover:scale-105 active:scale-95;
            }
            .puzzle-tile-empty {
                @apply bg-transparent cursor-default hover:scale-100 active:scale-100 shadow-none;
            }
            .btn-primary {
                @apply bg-primary hover:bg-primary/90 text-white font-bold py-2 px-4 rounded-lg transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-1;
            }
            .btn-secondary {
                @apply bg-secondary hover:bg-secondary/90 text-white font-bold py-2 px-4 rounded-lg transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-1;
            }
            .card {
                @apply bg-white rounded-xl shadow-lg p-6 transition-all duration-300 hover:shadow-xl;
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-indigo-50 to-purple-50 min-h-screen font-sans text-dark">
    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- 游戏标题 -->
        <header class="text-center mb-8">
            <h1 class="text-[clamp(2rem,5vw,3.5rem)] font-bold text-transparent bg-clip-text bg-gradient-to-r from-primary to-secondary mb-2">华容道拼图</h1>
            <p class="text-gray-600 text-lg max-w-2xl mx-auto">将数字按顺序排列，挑战你的逻辑思维和空间想象力！</p>
        </header>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 游戏区域 -->
            <div class="lg:col-span-2">
                <div class="card mb-6">
                    <div class="flex flex-wrap items-center justify-between mb-6">
                        <h2 class="text-2xl font-bold text-primary">游戏进行中</h2>
                        <div class="flex items-center gap-3">
                            <div class="flex items-center gap-2 bg-gray-100 rounded-lg px-4 py-2">
                                <i class="fa fa-clock-o text-accent"></i>
                                <span id="timer" class="font-bold">00:00</span>
                            </div>
                            <div class="flex items-center gap-2 bg-gray-100 rounded-lg px-4 py-2">
                                <i class="fa fa-refresh text-primary"></i>
                                <span id="moves" class="font-bold">0</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 关卡选择 -->
                    <div class="mb-6">
                        <label class="block text-gray-700 font-medium mb-2">选择关卡:</label>
                        <div class="flex flex-wrap gap-3">
                            <button class="level-btn btn-primary" data-level="1">关卡 1 (3x3)</button>
                            <button class="level-btn btn-primary" data-level="2">关卡 2 (4x4)</button>
                            <button class="level-btn btn-primary" data-level="3">关卡 3 (5x5)</button>
                            <button class="level-btn btn-primary" data-level="4">关卡 4 (6x6)</button>
                            <button class="level-btn btn-primary" data-level="5">关卡 5 (7x7)</button>
                        </div>
                    </div>
                    
                    <!-- 拼图容器 -->
                    <div class="relative w-full overflow-hidden" id="puzzle-container">
                        <div id="puzzle-board" class="grid grid-cols-3 gap-2 w-full h-full"></div>
                    </div>
                    
                    <!-- 控制按钮 -->
                    <div class="flex justify-center mt-6 gap-4">
                        <button id="shuffle-btn" class="btn-secondary">
                            <i class="fa fa-random mr-2"></i>重新开始
                        </button>
                        <button id="hint-btn" class="btn-secondary">
                            <i class="fa fa-lightbulb-o mr-2"></i>提示
                        </button>
                    </div>
                </div>
                
                <!-- 游戏统计 -->
                <div class="card">
                    <h2 class="text-2xl font-bold text-primary mb-4">游戏统计</h2>
                    <div class="w-full h-64" id="stats-chart"></div>
                </div>
            </div>
            
            <!-- 游戏规则和信息 -->
            <div class="lg:col-span-1">
                <div class="card sticky top-6">
                    <h2 class="text-2xl font-bold text-primary mb-4">游戏规则</h2>
                    
                    <div class="space-y-4">
                        <div class="flex items-start gap-3">
                            <div class="bg-primary/10 text-primary rounded-full w-8 h-8 flex items-center justify-center flex-shrink-0">
                                <i class="fa fa-info"></i>
                            </div>
                            <div>
                                <h3 class="font-bold text-lg mb-1">游戏目标</h3>
                                <p class="text-gray-600">通过移动数字方块，将所有数字按顺序排列。</p>
                            </div>
                        </div>
                        
                        <div class="flex items-start gap-3">
                            <div class="bg-primary/10 text-primary rounded-full w-8 h-8 flex items-center justify-center flex-shrink-0">
                                <i class="fa fa-hand-pointer-o"></i>
                            </div>
                            <div>
                                <h3 class="font-bold text-lg mb-1">如何移动</h3>
                                <p class="text-gray-600">点击与空白方块相邻的数字方块，它会移动到空白位置。</p>
                            </div>
                        </div>
                        
                        <div class="flex items-start gap-3">
                            <div class="bg-primary/10 text-primary rounded-full w-8 h-8 flex items-center justify-center flex-shrink-0">
                                <i class="fa fa-trophy"></i>
                            </div>
                            <div>
                                <h3 class="font-bold text-lg mb-1">胜利条件</h3>
                                <p class="text-gray-600">所有数字按顺序排列，空白方块位于右下角。</p>
                            </div>
                        </div>
                        
                        <div class="flex items-start gap-3">
                            <div class="bg-primary/10 text-primary rounded-full w-8 h-8 flex items-center justify-center flex-shrink-0">
                                <i class="fa fa-level-up"></i>
                            </div>
                            <div>
                                <h3 class="font-bold text-lg mb-1">关卡说明</h3>
                                <p class="text-gray-600">游戏共有5个关卡，从3x3到5x5难度递增，每个关卡的初始打乱步数不同。</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-8">
                        <h3 class="font-bold text-lg mb-3">游戏进度</h3>
                        <div id="level-progress" class="space-y-3">
                            <div class="flex items-center gap-3">
                                <span class="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center">1</span>
                                <div class="flex-1 h-4 bg-gray-200 rounded-full overflow-hidden">
                                    <div class="level-progress-bar h-full bg-primary rounded-full" style="width: 0%"></div>
                                </div>
                                <span class="level-progress-text font-medium">0%</span>
                            </div>
                            <div class="flex items-center gap-3">
                                <span class="w-8 h-8 rounded-full bg-gray-100 text-gray-600 flex items-center justify-center">2</span>
                                <div class="flex-1 h-4 bg-gray-200 rounded-full overflow-hidden">
                                    <div class="level-progress-bar h-full bg-primary rounded-full" style="width: 0%"></div>
                                </div>
                                <span class="level-progress-text font-medium">0%</span>
                            </div>
                            <div class="flex items-center gap-3">
                                <span class="w-8 h-8 rounded-full bg-gray-100 text-gray-600 flex items-center justify-center">3</span>
                                <div class="flex-1 h-4 bg-gray-200 rounded-full overflow-hidden">
                                    <div class="level-progress-bar h-full bg-primary rounded-full" style="width: 0%"></div>
                                </div>
                                <span class="level-progress-text font-medium">0%</span>
                            </div>
                            <div class="flex items-center gap-3">
                                <span class="w-8 h-8 rounded-full bg-gray-100 text-gray-600 flex items-center justify-center">4</span>
                                <div class="flex-1 h-4 bg-gray-200 rounded-full overflow-hidden">
                                    <div class="level-progress-bar h-full bg-primary rounded-full" style="width: 0%"></div>
                                </div>
                                <span class="level-progress-text font-medium">0%</span>
                            </div>
                            <div class="flex items-center gap-3">
                                <span class="w-8 h-8 rounded-full bg-gray-100 text-gray-600 flex items-center justify-center">5</span>
                                <div class="flex-1 h-4 bg-gray-200 rounded-full overflow-hidden">
                                    <div class="level-progress-bar h-full bg-primary rounded-full" style="width: 0%"></div>
                                </div>
                                <span class="level-progress-text font-medium">0%</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 胜利弹窗 -->
        <div id="win-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-xl shadow-2xl p-8 max-w-md w-full transform transition-all duration-500 scale-95 opacity-0" id="modal-content">
                <div class="text-center">
                    <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 text-green-500 mb-4">
                        <i class="fa fa-trophy text-3xl"></i>
                    </div>
                    <h2 class="text-3xl font-bold text-primary mb-2">恭喜你！</h2>
                    <p class="text-gray-600 mb-6" id="win-message">你已成功完成关卡 1！</p>
                    <div class="flex flex-col sm:flex-row gap-3 justify-center">
                        <button id="next-level-btn" class="btn-primary">
                            <i class="fa fa-arrow-right mr-2"></i>下一关
                        </button>
                        <button id="restart-level-btn" class="btn-secondary">
                            <i class="fa fa-refresh mr-2"></i>重新开始
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 提示弹窗 -->
        <div id="hint-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-xl shadow-2xl p-8 max-w-md w-full transform transition-all duration-500 scale-95 opacity-0" id="hint-modal-content">
                <div class="text-center">
                    <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-yellow-100 text-yellow-500 mb-4">
                        <i class="fa fa-lightbulb-o text-3xl"></i>
                    </div>
                    <h2 class="text-3xl font-bold text-primary mb-2">提示</h2>
                    <p class="text-gray-600 mb-6" id="hint-message">尝试移动与空白相邻的数字方块。</p>
                    <button id="close-hint-btn" class="btn-primary">
                        <i class="fa fa-check mr-2"></i>知道了
                    </button>
                </div>
            </div>
        </div>
        
        <footer class="mt-12 text-center text-gray-500 py-4">
            <p>华容道拼图小游戏 &copy; 2025 | 享受挑战逻辑的乐趣！</p>
        </footer>
    </div>

    <script>
        // 游戏数据
        var gameData = {
            currentLevel: 1,
            moves: 0,
            timer: 0,
            timerInterval: null,
            isPlaying: false,
            board: [],
            solution: [],
            emptyPos: { row: 0, col: 0 },
            levelData: [
                { size: 3, shuffleSteps: 20, name: "入门级" },
                { size: 4, shuffleSteps: 30, name: "简单级" },
                { size: 5, shuffleSteps: 40, name: "进阶级" },
                { size: 6, shuffleSteps: 50, name: "困难级" },
                { size: 7, shuffleSteps: 60, name: "专家级" }
            ],
            levelProgress: [0, 0, 0, 0, 0]
        };

        // DOM 元素
        var puzzleBoard = document.getElementById('puzzle-board');
        var puzzleContainer = document.getElementById('puzzle-container');
        var movesCounter = document.getElementById('moves');
        var timerDisplay = document.getElementById('timer');
        var shuffleBtn = document.getElementById('shuffle-btn');
        var hintBtn = document.getElementById('hint-btn');
        var levelBtns = document.querySelectorAll('.level-btn');
        var winModal = document.getElementById('win-modal');
        var modalContent = document.getElementById('modal-content');
        var winMessage = document.getElementById('win-message');
        var nextLevelBtn = document.getElementById('next-level-btn');
        var restartLevelBtn = document.getElementById('restart-level-btn');
        var hintModal = document.getElementById('hint-modal');
        var hintModalContent = document.getElementById('hint-modal-content');
        var hintMessage = document.getElementById('hint-message');
        var closeHintBtn = document.getElementById('close-hint-btn');
        var levelProgressBars = document.querySelectorAll('.level-progress-bar');
        var levelProgressTexts = document.querySelectorAll('.level-progress-text');

        // 初始化游戏
        function initGame() {
            // 加载游戏进度
            loadGameProgress();
            
            // 初始化第一关
            initLevel(1);
            
            // 初始化图表
            initStatsChart();
            
            // 更新进度条
            updateProgressBars();
            
            // 绑定事件
            bindEvents();
        }

        // 初始化关卡
        function initLevel(level) {
            // 停止当前计时器
            if (gameData.timerInterval) {
                clearInterval(gameData.timerInterval);
            }
            
            // 更新当前关卡
            gameData.currentLevel = level;
            var levelInfo = gameData.levelData[level - 1];
            
            // 更新UI
            levelBtns.forEach(function(btn, index) {
                if (index + 1 === level) {
                    btn.classList.add('bg-secondary');
                    btn.classList.remove('bg-primary');
                } else {
                    btn.classList.add('bg-primary');
                    btn.classList.remove('bg-secondary');
                }
            });
            
            // 重置游戏状态
            gameData.moves = 0;
            gameData.timer = 0;
            gameData.isPlaying = true;
            
            // 更新UI显示
            movesCounter.textContent = '0';
            timerDisplay.textContent = '00:00';
            
            // 创建解决方案
            createSolution(levelInfo.size);
            
            // 初始化棋盘
            initBoard(levelInfo.size);
            
            // 打乱棋盘
            shuffleBoard(levelInfo.shuffleSteps);
            
            // 开始计时器
            gameData.timerInterval = setInterval(updateTimer, 1000);
            
            // 调整棋盘大小
            adjustBoardSize(levelInfo.size);
        }

        // 创建解决方案（正确顺序）
        function createSolution(size) {
            gameData.solution = [];
            var value = 1;
            for (var i = 0; i < size; i++) {
                gameData.solution[i] = [];
                for (var j = 0; j < size; j++) {
                    if (i === size - 1 && j === size - 1) {
                        gameData.solution[i][j] = 0; // 空白方块
                    } else {
                        gameData.solution[i][j] = value++;
                    }
                }
            }
        }

        // 初始化棋盘
        function initBoard(size) {
            gameData.board = [];
            var value = 1;
            for (var i = 0; i < size; i++) {
                gameData.board[i] = [];
                for (var j = 0; j < size; j++) {
                    if (i === size - 1 && j === size - 1) {
                        gameData.board[i][j] = 0; // 空白方块
                        gameData.emptyPos = { row: i, col: j };
                    } else {
                        gameData.board[i][j] = value++;
                    }
                }
            }
            renderBoard();
        }

        // 渲染棋盘
        function renderBoard() {
            puzzleBoard.innerHTML = '';
            var size = gameData.board.length;
            puzzleBoard.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
            
            for (var i = 0; i < size; i++) {
                for (var j = 0; j < size; j++) {
                    var tileValue = gameData.board[i][j];
                    var tile = document.createElement('div');
                    
                    if (tileValue === 0) {
                        tile.className = 'puzzle-tile puzzle-tile-empty';
                    } else {
                        // 计算颜色
                        var hue = (tileValue * 360 / (size * size - 1)) % 360;
                        var color = `hsl(${hue}, 70%, 50%)`;
                        
                        tile.className = 'puzzle-tile';
                        tile.style.backgroundColor = color;
                        tile.style.fontSize = `clamp(1rem, 3vw, ${3 - size * 0.2}rem)`;
                        tile.textContent = tileValue;
                        tile.dataset.row = i;
                        tile.dataset.col = j;
                        
                        // 添加点击事件
                        tile.addEventListener('click', function() {
                            if (!gameData.isPlaying) return;
                            
                            var row = parseInt(this.dataset.row);
                            var col = parseInt(this.dataset.col);
                            
                            if (isAdjacent(row, col, gameData.emptyPos.row, gameData.emptyPos.col)) {
                                moveTile(row, col);
                                gameData.moves++;
                                movesCounter.textContent = gameData.moves;
                                
                                if (isSolved()) {
                                    gameCompleted();
                                }
                            }
                        });
                    }
                    
                    puzzleBoard.appendChild(tile);
                }
            }
        }

        // 打乱棋盘
        function shuffleBoard(steps) {
            var size = gameData.board.length;
            var lastDirection = null;
            
            // 记录移动历史，避免来回移动
            var moveHistory = [];
            
            for (var i = 0; i < steps; i++) {
                var possibleMoves = [];
                var row = gameData.emptyPos.row;
                var col = gameData.emptyPos.col;
                
                // 上
                if (row > 0 && lastDirection !== 'down') {
                    possibleMoves.push({ row: row - 1, col: col, direction: 'up' });
                }
                // 下
                if (row < size - 1 && lastDirection !== 'up') {
                    possibleMoves.push({ row: row + 1, col: col, direction: 'down' });
                }
                // 左
                if (col > 0 && lastDirection !== 'right') {
                    possibleMoves.push({ row: row, col: col - 1, direction: 'left' });
                }
                // 右
                if (col < size - 1 && lastDirection !== 'left') {
                    possibleMoves.push({ row: row, col: col + 1, direction: 'right' });
                }
                
                // 随机选择一个移动
                if (possibleMoves.length > 0) {
                    var randomIndex = Math.floor(Math.random() * possibleMoves.length);
                    var move = possibleMoves[randomIndex];
                    
                    // 移动方块
                    gameData.board[row][col] = gameData.board[move.row][move.col];
                    gameData.board[move.row][move.col] = 0;
                    gameData.emptyPos = { row: move.row, col: move.col };
                    
                    // 记录最后一个方向
                    lastDirection = move.direction;
                    
                    // 记录移动历史
                    moveHistory.push({ fromRow: move.row, fromCol: move.col, toRow: row, toCol: col });
                }
            }
            
            // 确保打乱后的拼图是可解的
            if (!isSolvable()) {
                // 如果不可解，交换两个非空白方块
                swapTwoTiles();
            }
            
            // 渲染棋盘
            renderBoard();
        }

        // 检查两个位置是否相邻
        function isAdjacent(row1, col1, row2, col2) {
            return (Math.abs(row1 - row2) === 1 && col1 === col2) || 
                   (Math.abs(col1 - col2) === 1 && row1 === row2);
        }

        // 移动方块
        function moveTile(row, col) {
            // 获取空白方块位置
            var emptyRow = gameData.emptyPos.row;
            var emptyCol = gameData.emptyPos.col;
            
            // 交换方块
            gameData.board[emptyRow][emptyCol] = gameData.board[row][col];
            gameData.board[row][col] = 0;
            
            // 更新空白方块位置
            gameData.emptyPos = { row: row, col: col };
            
            // 重新渲染棋盘
            renderBoard();
        }

        // 检查拼图是否已解决
        function isSolved() {
            var size = gameData.board.length;
            for (var i = 0; i < size; i++) {
                for (var j = 0; j < size; j++) {
                    if (gameData.board[i][j] !== gameData.solution[i][j]) {
                        return false;
                    }
                }
            }
            return true;
        }

        // 检查拼图是否可解
        function isSolvable() {
            // 仅对3x3和4x4有效
            var size = gameData.board.length;
            if (size !== 3 && size !== 4) return true;
            
            // 将棋盘转换为一维数组
            var flatBoard = [];
            for (var i = 0; i < size; i++) {
                for (var j = 0; j < size; j++) {
                    if (gameData.board[i][j] !== 0) {
                        flatBoard.push(gameData.board[i][j]);
                    }
                }
            }
            
            // 计算逆序数
            var inversions = 0;
            for (var i = 0; i < flatBoard.length; i++) {
                for (var j = i + 1; j < flatBoard.length; j++) {
                    if (flatBoard[i] > flatBoard[j]) {
                        inversions++;
                    }
                }
            }
            
            // 获取空白方块所在行
            var emptyRow = gameData.emptyPos.row;
            
            // 根据拼图大小判断是否可解
            if (size === 3) {
                // 3x3拼图：逆序数为偶数时可解
                return inversions % 2 === 0;
            } else {
                // 4x4拼图：空白在偶数行且逆序数为奇数，或空白在奇数行且逆序数为偶数时可解
                var emptyRowFromBottom = 4 - emptyRow;
                return (emptyRowFromBottom % 2 === 0 && inversions % 2 === 1) || 
                       (emptyRowFromBottom % 2 === 1 && inversions % 2 === 0);
            }
        }

        // 交换两个非空白方块
        function swapTwoTiles() {
            var size = gameData.board.length;
            var row1, col1, row2, col2;
            
            // 找到两个非空白方块
            do {
                row1 = Math.floor(Math.random() * size);
                col1 = Math.floor(Math.random() * size);
            } while (gameData.board[row1][col1] === 0);
            
            do {
                row2 = Math.floor(Math.random() * size);
                col2 = Math.floor(Math.random() * size);
            } while (gameData.board[row2][col2] === 0 || (row1 === row2 && col1 === col2));
            
            // 交换两个方块
            var temp = gameData.board[row1][col1];
            gameData.board[row1][col1] = gameData.board[row2][col2];
            gameData.board[row2][col2] = temp;
        }

        // 游戏完成
        function gameCompleted() {
            // 停止计时器
            clearInterval(gameData.timerInterval);
            gameData.isPlaying = false;
            
            // 更新进度
            var progress = Math.max(gameData.levelProgress[gameData.currentLevel - 1], 100);
            gameData.levelProgress[gameData.currentLevel - 1] = progress;
            
            // 保存进度
            saveGameProgress();
            
            // 更新进度条
            updateProgressBars();
            
            // 显示胜利信息
            var levelInfo = gameData.levelData[gameData.currentLevel - 1];
            winMessage.textContent = `恭喜你完成了 ${levelInfo.name} (${levelInfo.size}x${levelInfo.size})！用时 ${formatTime(gameData.timer)}，移动了 ${gameData.moves} 步。`;
            
            // 显示弹窗
            winModal.classList.remove('hidden');
            setTimeout(function() {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
            
            // 更新图表
            updateStatsChart();
        }

        // 更新计时器
        function updateTimer() {
            gameData.timer++;
            timerDisplay.textContent = formatTime(gameData.timer);
        }

        // 格式化时间
        function formatTime(seconds) {
            var mins = Math.floor(seconds / 60);
            var secs = seconds % 60;
            return (mins < 10 ? '0' + mins : mins) + ':' + (secs < 10 ? '0' + secs : secs);
        }

        // 调整棋盘大小
        function adjustBoardSize(size) {
            // 计算最佳尺寸
            var containerWidth = puzzleContainer.offsetWidth;
            var tileSize = Math.floor(containerWidth / size);
            
            // 设置棋盘高度
            puzzleBoard.style.height = `${tileSize * size}px`;
            
            // 设置每个方块的大小
            var tiles = puzzleBoard.querySelectorAll('.puzzle-tile');
            tiles.forEach(function(tile) {
                tile.style.height = `${tileSize}px`;
            });
        }

        // 绑定事件
        function bindEvents() {
            // 洗牌按钮
            shuffleBtn.addEventListener('click', function() {
                initLevel(gameData.currentLevel);
            });
            
            // 提示按钮
            hintBtn.addEventListener('click', function() {
                if (!gameData.isPlaying) return;
                
                // 获取空白方块位置
                var emptyRow = gameData.emptyPos.row;
                var emptyCol = gameData.emptyPos.col;
                var size = gameData.board.length;
                
                // 查找正确位置不在当前位置的方块
                var hintTile = null;
                for (var i = 0; i < size; i++) {
                    for (var j = 0; j < size; j++) {
                        var value = gameData.board[i][j];
                        if (value === 0) continue;
                        
                        // 找到这个值在solution中的位置
                        var correctRow = Math.floor((value - 1) / size);
                        var correctCol = (value - 1) % size;
                        
                        // 如果当前位置不是正确位置
                        if (i !== correctRow || j !== correctCol) {
                            // 检查是否与空白相邻
                            if (isAdjacent(i, j, emptyRow, emptyCol)) {
                                hintTile = { row: i, col: j };
                                break;
                            }
                        }
                    }
                    if (hintTile) break;
                }
                
                // 如果没有找到，提供通用提示
                if (!hintTile) {
                    hintMessage.textContent = "尝试移动与空白方块相邻的数字，逐步将数字归位。";
                } else {
                    hintMessage.textContent = `移动数字 ${gameData.board[hintTile.row][hintTile.col]} 可能是一个好选择。`;
                }
                
                // 显示提示弹窗
                hintModal.classList.remove('hidden');
                setTimeout(function() {
                    hintModalContent.classList.remove('scale-95', 'opacity-0');
                    hintModalContent.classList.add('scale-100', 'opacity-100');
                }, 10);
            });
            
            // 关卡按钮
            levelBtns.forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var level = parseInt(this.dataset.level);
                    initLevel(level);
                });
            });
            
            // 下一关按钮
            nextLevelBtn.addEventListener('click', function() {
                // 隐藏弹窗
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');
                
                setTimeout(function() {
                    winModal.classList.add('hidden');
                    
                    // 进入下一关
                    var nextLevel = gameData.currentLevel + 1;
                    if (nextLevel <= gameData.levelData.length) {
                        initLevel(nextLevel);
                    } else {
                        // 所有关卡完成
                        alert("恭喜你完成了所有关卡！");
                        initLevel(1);
                    }
                }, 300);
            });
            
            // 重新开始按钮
            restartLevelBtn.addEventListener('click', function() {
                // 隐藏弹窗
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');
                
                setTimeout(function() {
                    winModal.classList.add('hidden');
                    
                    // 重新开始当前关卡
                    initLevel(gameData.currentLevel);
                }, 300);
            });
            
            // 关闭提示按钮
            closeHintBtn.addEventListener('click', function() {
                // 隐藏弹窗
                hintModalContent.classList.remove('scale-100', 'opacity-100');
                hintModalContent.classList.add('scale-95', 'opacity-0');
                
                setTimeout(function() {
                    hintModal.classList.add('hidden');
                }, 300);
            });
            
            // 窗口大小变化时调整棋盘
            window.addEventListener('resize', function() {
                var levelInfo = gameData.levelData[gameData.currentLevel - 1];
                adjustBoardSize(levelInfo.size);
            });
        }

        // 初始化统计图表
        function initStatsChart() {
            var chartDom = document.getElementById('stats-chart');
            var myChart = echarts.init(chartDom);
            
            // 指定图表的配置项和数据
            var option = {
                title: {
                    text: '关卡完成情况',
                    left: 'center',
                    textStyle: {
                        color: '#4F46E5',
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: ['关卡 1', '关卡 2', '关卡 3', '关卡 4', '关卡 5'],
                    axisLabel: {
                        color: '#6B7280'
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '完成度 (%)',
                    min: 0,
                    max: 100,
                    axisLabel: {
                        color: '#6B7280'
                    }
                },
                series: [{
                    name: '完成度',
                    data: gameData.levelProgress,
                    type: 'bar',
                    color: '#4F46E5',
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%'
                    }
                }]
            };
            
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
            
            // 存储图表实例
            gameData.statsChart = myChart;
        }

        // 更新统计图表
        function updateStatsChart() {
            if (gameData.statsChart) {
                gameData.statsChart.setOption({
                    series: [{
                        data: gameData.levelProgress
                    }]
                });
            }
        }

        // 更新进度条
        function updateProgressBars() {
            gameData.levelProgress.forEach(function(progress, index) {
                levelProgressBars[index].style.width = `${progress}%`;
                levelProgressTexts[index].textContent = `${progress}%`;
                
                // 如果关卡已完成，高亮显示
                if (progress >= 100) {
                    levelProgressBars[index].classList.add('bg-secondary');
                    levelProgressBars[index].classList.remove('bg-primary');
                } else {
                    levelProgressBars[index].classList.add('bg-primary');
                    levelProgressBars[index].classList.remove('bg-secondary');
                }
            });
        }

        // 保存游戏进度
        function saveGameProgress() {
            try {
                var progressData = {
                    levelProgress: gameData.levelProgress
                };
                localStorage.setItem('puzzleGameProgress', JSON.stringify(progressData));
            } catch (e) {
                console.error('Failed to save game progress:', e);
            }
        }

        // 加载游戏进度
        function loadGameProgress() {
            try {
                var progressData = localStorage.getItem('puzzleGameProgress');
                if (progressData) {
                    var parsedData = JSON.parse(progressData);
                    gameData.levelProgress = parsedData.levelProgress || [0, 0, 0, 0, 0];
                }
            } catch (e) {
                console.error('Failed to load game progress:', e);
            }
        }

        // 启动游戏
        document.addEventListener('DOMContentLoaded', initGame);
    </script>
</body>
</html>